package org.jeecgframework.web.tcdev.controller;

import com.tchy.cloud.tools.Tools;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.tcdev.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by chenghao on 2015/4/9.
 */
@Controller
@RequestMapping("/adController")
public class AdController {
    private static final Logger logger = Logger.getLogger(AdController.class);

    @Autowired
    private AdService adService;

    @Autowired
    private SystemService systemService;

    private String message;

    /**
     * 广告显示页面
     *
     * @return
     */
    @RequestMapping(params = "ad")
    public ModelAndView ad(String pid, HttpServletRequest req) {
        req.setAttribute("pid", pid);
        return new ModelAndView("tcdev/ad/adList");
    }

    /**
     * easyuiAJAX请求数据
     */
    @RequestMapping(params = "adGrid")
    public void adGrid(HttpServletResponse response, DataGrid dataGrid, String pid) {
        List<Map<String, Object>> ll = adService.listAll(Integer.valueOf(pid), dataGrid.getPage(), dataGrid.getRows());
        Integer count = adService.getCount(Integer.valueOf(pid));

        dataGrid.setTotal(count);
        dataGrid.setResults(ll);

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 列表页面跳转
     *
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(@RequestParam Map<String, String> m, HttpServletRequest req) {
        String aid = m.get("id");
        String pid = m.get("pid");
        if (StringUtil.isNotEmpty(aid)) {
            int id = Integer.parseInt(aid);
            Map<String, Object> map = adService.getAdInfoById(id);
            req.setAttribute("map", map);
        }
        req.setAttribute("pid", pid);
        return new ModelAndView("tcdev/ad/ad");
    }

    /**
     * 添加或编辑广告
     *
     * @param m
     * @return
     */
    @RequestMapping(params = "saveAd")
    @ResponseBody
    public AjaxJson saveAd(@RequestParam Map<String, Object> m) {
        AjaxJson j = new AjaxJson();

        if (StringUtil.isNotEmpty(m.get("id"))) {
            try {
                adService.updateAd(m);
                message = "更新广告成功";
            } catch (Exception e) {
                logger.error("更新广告失败", e);
                message = "更新广告失败";
            }

            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } else {
            try {
                adService.saveAd(m);
                message = "新增广告成功";
            } catch (Exception e) {
                logger.error("新增广告失败", e);
                message = "新增广告失败";
            }
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 广告位置显示页面
     *
     * @return
     */
    @RequestMapping(params = "adPosition")
    public ModelAndView adPosition(String adId, HttpServletRequest req) {
        req.setAttribute("adId", adId);
        return new ModelAndView("tcdev/ad/adPositionList");
    }

    /**
     * easyuiAJAX请求数据
     */
    @RequestMapping(params = "adPositionGrid")
    public void adPositionGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        List<Map<String, Object>> ll = adService.adPositionListAll(dataGrid.getPage(), dataGrid.getRows());
        Integer count = adService.getPositionCount();

        dataGrid.setTotal(count);
        dataGrid.setResults(ll);

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 列表页面跳转
     *
     * @return
     */
    @RequestMapping(params = "addorupdateAdPosition")
    public ModelAndView addorupdateAdPosition(@RequestParam Map<String, String> m, HttpServletRequest req) {
        String pid = m.get("id");
        if(StringUtil.isNotEmpty(pid)){
            Map<String, Object> map = adService.getAdPosition(Integer.valueOf(pid));
            req.setAttribute("map", map);
        }

        return new ModelAndView("tcdev/ad/adPosition");
    }

    /**
     * 添加或编辑广告位置
     *
     * @param m
     * @return
     */
    @RequestMapping(params = "saveAdPosition")
    @ResponseBody
    public AjaxJson saveAdPosition(@RequestParam Map<String, Object> m) {
        AjaxJson j = new AjaxJson();

        try {
            adService.saveUpdateAdPosition(m);
            message = "设置广告位置成功";
        } catch (Exception e) {
            logger.error("设置广告位置失败", e);
            message = "设置广告位置失败";
        }

        Object pid = m.get("id");
        if (StringUtil.isNotEmpty(pid)) { //不为空
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        }else {

            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }



        j.setMsg(message);
        return j;
    }

    @RequestMapping(params = "delAdPosition")
    @ResponseBody
    public AjaxJson delAdPosition(String id){
        AjaxJson j = new AjaxJson();
        try {
            adService.delAdPosition(Integer.valueOf(id));
            message = "删除广告成功";
        } catch (Exception e) {
            logger.error("删除广告失败", e);
            message = "删除广告失败";
        }

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }

    @RequestMapping(params = "delAdInfo")
    @ResponseBody
    public AjaxJson delAdInfo(String id){
        AjaxJson j = new AjaxJson();
        try {
            adService.delAdInfo(Integer.valueOf(id));
            message = "删除广告信息成功";
        } catch (Exception e) {
            logger.error("删除广告信息失败", e);
            message = "删除广告信息失败";
        }

        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

        j.setMsg(message);
        return j;
    }

    /**
     * 上传图片
     * @param file
     * @param request
     * @param response
     */
    @RequestMapping(params = "uploadAdPic")
    public void upload_resource_file(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, final HttpServletResponse response) {
        try {
            //读取上传文件相对路径
            //String fileUrl = ReadProperties.getInstance().getValue("/META-INF/system.properties","mis_flie_upload_url");
            String fileUrl = "upload/ad_pic";
            //得到上传文件绝对路径
            String path = request.getSession().getServletContext().getRealPath(fileUrl);
            // String fileName = file.getOriginalFilename(); //文件原名

            /** 获取文件的后缀* */
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            //文件名以时间戳命名
            String fileName = System.currentTimeMillis() + suffix;

            //去掉文件名中的空格，避免下载出错
            fileName = fileName.replaceAll(" ", "");

            if ("".equals(fileName)) {
                return;
            }
            //文件夹名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String folderName = sdf.format(new Date().getTime());

            path += "//" + folderName;

            //创建文件夹及文件
            File targetFile = Tools.getFileByOriginalFileName(path, fileName, 2);

            //保存文件
            file.transferTo(targetFile);
            String new_fileName = targetFile.getName();

            String strUrl = fileUrl + "/" + folderName + "/" + new_fileName;

            //设置返回头
            response.setContentType("text/html");
            response.getWriter().print(strUrl + "," + new_fileName);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }
}
